// pages/products/product.js
var app = getApp();
var currentShopId = 0;
var currentProductId = 0;
var WxParse = require('../../wxParse/wxParse.js');
function withData(param) {
    return param < 10 ? '0' + param : '' + param;
}
Page({
    data: {
        hideCartAS: true,
        showModal: false,
        share: false,
        isZan: false,
        curSpecIndex: 0,
        minusSrc: '/images/can-minus.png',
        plusSrc: '/images/can-plus.png',
        mstime: 0,
        timestamp:0,
    },
    onLoad: function (options) {
       
        console.log(options)
        // 页面初始化 options为页面跳转所带来的参数
        var that = this;
        // console.log(options)
       if(options.mid){
           this.setData({
               mid: options.mid
           })
       }
        if (options.share) {
            this.setData({
                share: true
            })
        }
        if(options.shop_id && options.product_id){
            this.setData({
                shop_id:options.shop_id,
                product_id:options.product_id
            });
            wx.setStorageSync('shop_id', options.shop_id);
        }

        app.util.newLogin(app, function (res) {
            if (res == 'error') {
                var token = wx.getStorageSync('token');
                if (!token) {
                    that.setData({
                        showModalAuth: true,
                    })
                }
            }        
        });


        //获取店铺id
        currentShopId = wx.getStorageSync('shop_id');
        currentProductId = options.product_id;
        if (options.shop_id) {
            currentShopId = options.shop_id;
        } 
        var carts = wx.getStorageSync('carts');
        var cart = {
            shopId: currentShopId,
            products: []
        };
        if (!carts) {
            carts = [cart]
        }
        carts.forEach(function (everycart) {
            if (everycart.shopId == currentShopId) {
                cart = everycart;
            }
        })
        console.log(carts)
        this.setData({ cart: cart })
        app.func.req('shops/show', {
            id: currentShopId
        }, 'GET', function (res) {
            //TODO: refactor
            that.setData({
                shop: res.result
            });
        }, {
                'token': wx.getStorageSync('token')
            });
        that.getProduct();
        setInterval(function () {
            this.countDown();
        }.bind(this), 1000)
    },
    clickinfo: function () {
        this.setData({
            showModalAuth: false,
        })
    },
    newlogin: function (e) {
        var that = this;
        if (e.detail.errMsg != 'getUserInfo:fail auth deny' && e.detail.userInfo) {
            wx.login({
                success: function (res) {
                    var nickname = e.detail.userInfo.nickName;
                    var avatar = e.detail.userInfo.avatarUrl;


                    //授权登录，获取3rd_session
                    app.func.req("index/wx_xcx_login", { code: res.code, app_id: app.app_id, nickname: nickname, avatar: avatar }, "GET", function (res) {
                        console.log(res);
                        var session_3rd = res.result.session_3rd;
                        var token = res.result.token;

                        try {
                            wx.setStorageSync('token', token);
                            wx.setStorageSync('session_3rd', session_3rd);
                        } catch (e) {
                            console.log(e)
                        }
                        

                        //获取店铺id
                        currentShopId = that.data.shop_id;
                        currentProductId = that.data.product_id;
                        var carts = wx.getStorageSync('carts');
                        var cart = {
                            shopId: currentShopId,
                            products: []
                        };
                        if (!carts) {
                            carts = [cart]
                        }
                        carts.forEach(function (everycart) {
                            if (everycart.shopId == currentShopId) {
                                cart = everycart;
                            }
                        })
                        console.log(carts)
                       that.setData({ cart: cart })
                        app.func.req('shops/show', {
                            id: currentShopId
                        }, 'GET', function (res) {
                            //TODO: refactor
                            that.setData({
                                shop: res.result
                            });
                        }, {
                                'token': wx.getStorageSync('token')
                            });
                        that.getProduct();






                    });
                },
                fail: function () {
                    wx.login();
                }
            });
        }
        //app.util.newLogin(app,function(res){});
    },
    productsShow:function(){
        var that = this;
        app.func.req('products/show', {
            shop_id: currentShopId,
            id: currentProductId
        }, 'GET', function (res) {
            console.log(res);
            if (res.result.status == 0) {
                wx.showToast({
                    title: '该商品未上架',
                    image: '/images/fail.png',
                    duration: 2000
                });
            }
            var product = {};
            product.id = res.result.id;
            product.logo = res.result.logo;
            product.name = res.result.name;
            product.price = res.result.price;
            product.product_num = res.result.product_num;
            product.proxy_price = res.result.proxy_price;
            product.num = 0;
            product.specs = res.result.spec;
            product.is_limit = res.result.is_limit;
            if (res.result.is_limit > 0) {
                product.limit_num = res.result.limit_num;
            }
            product.updated_at = res.result.updated_at;
            if (product.specs) {
                for (var i = 0; i < product.specs.length; i++) {
                    product.specs[i].num = 0;
                    //delete product.specs[i].id;
                }
            }
            var start_at = res.result.zan_started_at;
            var end_at = res.result.zan_ended_at;
            var is_zan = res.result.is_zan;
            var s_time = '';

            if (res.result.is_zan) {
                var now = new Date();
                var time = new Date(end_at.replace(/\-/g, '/').replace('.0', '')) - now;
                var t = setInterval(function () {
                    time = time - 1000;
                    if (time < 1000) {
                        clearInterval(t);
                        s_time = '已结束';
                    } else {
                        var days = Math.floor(time / (1000 * 60 * 60 * 24));
                        var hours = Math.floor((time - days * 24 * 60 * 60 * 1000) / (1000 * 60 * 60));
                        var minutes = Math.floor((time - days * 24 * 60 * 60 * 1000 - hours * 60 * 60 * 1000) / (1000 * 60));
                        var second = Math.floor((time - days * 24 * 60 * 60 * 1000 - hours * 60 * 60 * 1000 - minutes * 60 * 1000) / (1000));
                        s_time = '离结束还有' + days + '天' + hours + '小时' + minutes + '分' + second + '秒';
                    }
                    that.setData({
                        s_time: s_time
                    })
                }, 1000);
            }
            var transData = WxParse.wxParse('content', 'html', res.result.content, that, 0);

            that.setData({
                product: res.result,
                curProduct: product
            });
        }, {
                'token': wx.getStorageSync('token')
            });
    },
    getProduct: function () {
        var that = this;
        if(that.data.mid)
        app.func.req('ms_products/show', {
            id: that.data.mid
        }, 'GET', function (res) {
            console.log(res)
            var sale_percent;       
            res.result.specs=[1,2,3]; // 3表示库存。 记得删除测试数据        
            if (res.code == "success") {
                if(res.result.specs.length!=0) {
                    if(res.result.product_num==0) sale_percent = "100.00%";
                    else  sale_percent = ((res.result.product_num - res.result.specs[2]) / res.result.product_num) .toFixed(2)+"%";
                }
                else {
                    sale_percent = "0.00%";
                }
                var nowtime = Date.parse(new Date());
                var start_time = (parseInt(res.result.start_time) + 60 * 60 * 26)*1000;
                var end_time = (parseInt(res.result.end_time) + 60 * 60 * 26)*1000;
                console.log(start_time,end_time,nowtime)
                var mstime ;
                if (start_time > nowtime){
                    var showtime = start_time - nowtime;
                    mstime = that.timestamp_to_time(showtime);
                    that.setData({
                        toStart: true
                    })
                }
                else if (start_time < nowtime && end_time > nowtime){
                    var showtime = end_time - nowtime;
                    mstime = that.timestamp_to_time(showtime);
                    that.setData({
                        toEnd: true
                    })
                }
                else{
                    that.setData({
                        alreadyEnd: true
                    })
                }
                console.log(mstime)
                that.setData({
                    ms: true,
                    ms_info: res.result,
                    sale_percent: sale_percent,
                    mstime: mstime,
                    timestamp: showtime
                })
                that.productsShow();    
            }  
                

        }, {
                token: wx.getStorageSync('token')
            })

        else{
            that.productsShow();  
        }
        
    },
    previewImage: function (e) {
        var that = this;
        var index = e.target.dataset.index;
        wx.previewImage({
            current: that.data.product.photos[index],
            urls: that.data.product.photos
        })
    },
    hideAttrPicker: function(){
        this.setData({
            showBuyModal:false,
        })
    },
    showSpecs: function () {
        this.setData({
            is_express: false,
            showBuyModal: true

        })
    },
    buy: function () {
        var curProduct = this.data.curProduct;
            this.setData({
                showBuyModal: true
            })

         if (curProduct.specs.length == 0) {
            if(curProduct.num <=0 || curProduct.product_num < curProduct.num){
                curProduct.num=1
                this.setData({
                    curProduct:curProduct,
                })
            };
         } else if (curProduct.specs.length > 0) {

            var defaults = true;
            var indexx = 99;
            curProduct.specs.forEach(function(item,index,array){
                if(item['stock']>0 && indexx==99){
                    indexx = index;
                }
                if(item['checked']){
                  defaults = false;  
                }
            })

            if(defaults){
                curProduct.specs[indexx].checked = true;
                curProduct.specs[indexx].num = 1;
                this.setData({
                    curProduct:curProduct,
                    curSpecIndex:indexx,
                })
            }
         }
     },
    specBuy: function () {
        var curProduct = this.data.curProduct;
        var curSpecIndex = this.data.curSpecIndex;
        if (curProduct.is_limit > 0 && curProduct.specs[curSpecIndex].limit_num == 0) {
            wx.showToast({
                title: '限购' + curProduct.is_limit + '个',
                image: '/images/fail.png',
                duration: 2000
            });
        } else {
            curProduct.specs.forEach(function (spec, index) {
                if (index == curSpecIndex) {
                    spec.num = 1;
                } else {
                    spec.num = 0;
                }
            })

            this.setData({
                curProduct: curProduct,
                showModal: false,
                showBuyModal: true
            })
        }
    },
    zanbuy: function () {
        var curProduct = this.data.curProduct
        if (this.data.product.buy_able) {
            curProduct.price = this.data.product.zan_price;
            curProduct.num = 1;
            this.setData({
                isZan: true,
                curProduct: curProduct
            });
            this.createOrder();
        }
    },
    closeModal: function () {
        this.setData({
            showModal: false,
            showBuyModal: false
        })
    },
    // 规格切换
    toggleSpec: function (e) {
        var index = e.target.dataset.index;
        this.setData({
            curSpecIndex: index
        })
    },
    onShareAppMessage: function () {
        var nickname = wx.getStorageSync('nickname');
        if (!nickname) {
            nickname = ''
        }

        return {
            title: nickname + '分享了' + this.data.product.name,
            imageUrl: this.data.product.logo.replace(/(^\s*)|(\s*$)/g, ""),
            path: 'pages/share/share?product_id=' + this.data.product.id + '&&shop_id=' + currentShopId + '&&product_share=true'
        }
    },
    zan: function (e) {
        if (!wx.canIUse('button.open-type.getUserInfo')) {
            wx.showModal({
                title: '提示',
                content: '请升级手机微信版本6.5.10及以上',
                showCancel: false
            })
            return;
        }

        var that = this;
        if (e.detail.errMsg == 'getUserInfo:ok') {
            //是否更新过用户信息
            var userInfoExist = wx.getStorageSync('userInfoExist');
            if (!userInfoExist) {
                app.util.userAuth(app, e.detail, function (res) {
                    wx.setStorageSync('userInfoExist', true);
                    that.goZan();
                });
            } else {
                that.goZan();
            }
        } else {
            wx.showToast({
                title: '授权后才能参与点赞',
                image: '/images/fail.png',
                duration: 2000
            });
        }
    },
    goZan: function () {
        var that = this;
        app.func.req('products/zan', {
            product_id: that.data.curProduct.id
        }, 'POST', function (res) {
            if (res.code == "success") {
                that.getProduct();
                if (res.result.win == 'true') {
                    wx.showModal({
                        title: '恭喜您',
                        content: '恭喜您成为点赞幸运用户，可以以点赞优惠价购买本商品哦！！',
                        showCancel: false,
                        confirmText: '朕知道了'
                    })
                } else {
                    wx.showModal({
                        title: '提示',
                        content: '很遗憾没有成为幸运用户，感谢参与！',
                        showCancel: false,
                        confirmText: '朕知道了'
                    })
                }
            }
        }, {
                'token': wx.getStorageSync('token')
            })
    },
    addCart: function () {
        var carts = wx.getStorageSync('carts');
        var num = 0;
        var product = this.data.curProduct;
        if (product.specs.length == 0) {
            if (product.is_limit > 0 && product.limit_num == 0) {
                wx.showToast({
                    title: '限购' + product.is_limit + '个',
                    image: '/images/fail.png',
                    duration: 2000
                });
                return false
            }
            num = product.num;

        } else if (product.specs.length > 0) {
            if (product.is_limit > 0 && product.specs[this.data.curSpecIndex].limit_num == 0) {
                wx.showToast({
                    title: '限购' + product.is_limit + '个',
                    image: '/images/fail.png',
                    duration: 2000
                });
                return false
            }

            product.specs.forEach(function(item,index,array){
                if(item.checked){
                    num = item.num;
                }
            });
        }
        var cart = {
            shopId: currentShopId,
            products: [product]
        };
        if (!carts) {
            carts = [cart]
        }
        var isset_cart = false;
        for (var i = 0; i < carts.length; i++) {
            if (carts[i].shopId == currentShopId) {
                cart = carts[i];
                isset_cart = true;
            }
        }
        var isset_product = false;
        for (var j = 0; j < cart.products.length; j++) {
            if (cart.products[j].id == currentProductId) {
                product = cart.products[j];
                isset_product = true;
            }
        }
        if(num==0){
           num =1;
        }
        if (product.specs.length == 0) {
            product.num = num;
        } else {
            product.specs[this.data.curSpecIndex].num = num;
        }
        if (!isset_cart) {
            carts.push(cart)
        } else if (isset_cart && !isset_product) {
            cart.products.push(product)
        }
        wx.setStorage({
            key: 'carts',
            data: carts,
        })
        this.closeModal()
        this.setData({ cart: cart })
        wx.showToast({
            title: '添加成功'
        })
    },
    showContact: function () {
        this.setData({
            showContact: true
        })
    },
    closeContact: function () {
        this.setData({
            showContact: false
        })
    },
    telPhone: function () {
        var that = this;
        var shop = that.data.shop;
        var phone = shop.kfphone ? shop.kfphone : shop.phone;
        wx.makePhoneCall({
            phoneNumber: phone
        })
    },
    cartMinus: function (e) {
        var that = this;
        var specIndex = e.target.dataset.index;

        var curProduct = this.data.curProduct;
        if (curProduct.specs.length == 0) {
            if (curProduct.num > 1) {
                curProduct.num--;
                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            } else {
                curProduct.num == 0;
                that.setData({
                    minusSrc: "/images/cannot-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            }
        } else if (curProduct.specs.length > 0) {
            if (curProduct.specs[specIndex].num > 1) {
                curProduct.specs[specIndex].num--;
                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            } else {
                curProduct.specs[specIndex].num == 1;
                that.setData({
                    minusSrc: "/images/cannot-minus.png",
                    plusSrc: "/images/can-plus.png"
                })
            }
        }
        that.setData({
            curProduct: curProduct
        })
    },
    setNum: function (e) {
        var that = this;
        var specIndex = e.target.dataset.index;
        var curProduct = this.data.curProduct;
        var num = Math.ceil(e.detail.value);
        if (num < 1) {
            num = 1;
        }

        if (curProduct.specs.length == 0) {
            if (curProduct.is_limit > 0 && curProduct.limit_num < num) {
                num = curProduct.limit_num;
                wx.showToast({
                    title: '限购' + curProduct.is_limit + '个',
                    image: '/images/fail.png',
                    duration: 2000
                });
            }
            if (curProduct.product_num < num) {
                num = curProduct.product_num;
                wx.showToast({
                    title: '最多购买' + num + '个',
                    image: '/images/fail.png',
                    duration: 2000
                });
            }
            curProduct.num = num;
        } else if (curProduct.specs.length > 0) {
            if (curProduct.is_limit > 0 && curProduct.specs[specIndex].limit_num < num) {
                num = curProduct.specs[specIndex].limit_num;
                wx.showToast({
                    title: '限购' + curProduct.is_limit + '个',
                    image: '/images/fail.png',
                    duration: 2000
                });
            }else{
                if(num > curProduct.specs[specIndex].stock){
                    wx.showToast({
                        title: '最多购买' + curProduct.specs[specIndex].stock + '个',
                        image: '/images/fail.png',
                        duration: 2000
                    });
                    that.setData({
                        minusSrc: "/images/can-minus.png",
                        plusSrc: "/images/cannot-plus.png"
                    })
                    curProduct.specs[specIndex].num =curProduct.specs[specIndex].stock;
                }else{
                    that.setData({
                        minusSrc: "/images/can-minus.png",
                        plusSrc: "/images/can-plus.png"
                    })
                    curProduct.specs[specIndex].num = num;
                }
            }
        }

        that.setData({
            curProduct: curProduct
        })
    },
    clearNum: function (e) {
        var that = this;
        var specIndex = e.target.dataset.index;
        var curProduct = this.data.curProduct;

        if (curProduct.specs.length == 0) {
            curProduct.num = '';
        } else if (curProduct.specs.length > 0) {
            curProduct.specs[specIndex].num = null;
        }

        that.setData({
            curProduct: curProduct
        })
    },
    cartPlus: function (e) {
        var that = this;
        var specIndex = e.target.dataset.index;
        var curProduct = this.data.curProduct;

        if (curProduct.specs.length == 0) {
            if (curProduct.is_limit > 0 && curProduct.limit_num < curProduct.num + 1) {
                wx.showToast({
                    title: '限购' + curProduct.is_limit + '个',
                    image: '/images/fail.png',
                    duration: 2000
                });
                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: '/images/cannot-plus.png'
                })
            } else {
                if(curProduct.num + 1 > curProduct.product_num){
                    wx.showToast({
                        title: '最多购买' + curProduct.product_num + '个',
                        image: '/images/fail.png',
                        duration: 2000
                    });
                    that.setData({
                        minusSrc: "/images/can-minus.png",
                        plusSrc: '/images/cannot-plus.png'
                    })
                }else{
                    curProduct.num++;
                    that.setData({
                        minusSrc: "/images/can-minus.png",
                        plusSrc: "/images/can-plus.png"
                    })                    
                }

            }
        } else if (curProduct.specs.length > 0) {
            if (curProduct.is_limit > 0 && curProduct.specs[specIndex].limit_num < curProduct.specs[specIndex].num + 1) {
                wx.showToast({
                    title: '限购' + curProduct.is_limit + '个',
                    image: '/images/fail.png',
                    duration: 2000
                });
                that.setData({
                    minusSrc: "/images/can-minus.png",
                    plusSrc: "/images/cannot-plus.png"
                })
            } else {
                if(curProduct.specs[specIndex].num + 1 > curProduct.specs[specIndex].stock){
                    wx.showToast({
                        title: '最多购买' + curProduct.specs[specIndex].stock + '个',
                        image: '/images/fail.png',
                        duration: 2000
                    });
                    curProduct.specs[specIndex].num = curProduct.specs[specIndex].stock;
                }else{
                    curProduct.specs[specIndex].num++;
                    that.setData({
                        minusSrc: "/images/can-minus.png",
                        plusSrc: "/images/can-plus.png"
                    })
               
                }
            }
        }

        that.setData({
            curProduct: curProduct
        })
    },
    createOrder: function () {
        var that = this;
        var curProduct = this.data.curProduct;
        var expressCart = {
            shopId: currentShopId,
            products: [curProduct],
            total: 0,
            count: 0
        }
        var specs = false;
        if (curProduct.specs.length == 0) {
            expressCart.total = curProduct.num * curProduct.price;
            expressCart.count = curProduct.num
            curProduct.checked = true;            

            if(expressCart.count > this.data.product.product_num){
                wx.showModal({
                    title: '提示',
                    content: '库存不足',
                    showCancel: false,
                    confirmText: '朕知道了'
                })
                return;
            }
        } else if (curProduct.specs.length > 0) {
            curProduct.specs.forEach(function (spec) {
                if (spec.checked == true) {
                    if(spec.num > spec.stock){
                       specs = true;
                    };
                    spec.checked = true;
                    expressCart.total += Number(spec.num * spec.price);
                    expressCart.count += spec.num;
                }else{
                    spec.num = 0;
                }
            }) 
            if(specs){
                wx.showModal({
                    title: '提示',
                    content: '库存不足',
                    showCancel: false,
                    confirmText: '朕知道了'
                })
                return;
            }
        }
        expressCart.total = Math.round(expressCart.total * 100) / 100;

        expressCart.is_zan = this.data.isZan;
        expressCart.is_platform = this.data.product.is_platform == 1;
        if (expressCart.total > 0) {
            wx.setStorage({
                key: 'expressCart',
                data: expressCart,
                success: function () {
                    wx.navigateTo({
                        url: '/pages/orders/order_confirm?is_express=true'
                    });
                }
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '请选择至少一件商品',
                showCancel: false,
                confirmText: '朕知道了'
            })
        }

    },
    countDown() {
        var _time = this.data.timestamp;
        if (_time >= 1000){
            _time =_time-1000;
        }
        else{
            this.setData({
                alreadyEnd: true,
                toStart:false,
                toEnd:false
            })
        }
        var mstime = this.timestamp_to_time(_time);
        this.setData({
            mstime: mstime,
            timestamp: _time
        })
    },
    timestamp_to_time(showtime) {
        var hour = Math.floor(showtime / (60 * 60 * 1000));
        hour = withData(hour);
        var minute = Math.floor((showtime - hour * (60 * 60 * 1000)) / (60 * 1000));
        minute = withData(minute);
        var second = Math.floor((showtime - minute * (60 * 1000) - hour * (60 * 60 * 1000)) / 1000);
        second = withData(second);
        return hour + ":" + minute + ":" + second;
    },
    copyWechat(){
        var that =this;
        var phone ;
        this.data.shop.kfphone ? phone = this.data.shop.kfphone : phone=this.data.shop.phone;
        wx.setClipboardData({
            data: phone,
            success: function (res) {
                wx.showToast({
                    title: '复制成功',
                    icon: 'success',
                    duration: 2000
                })
                wx.getClipboardData({
                    success: function (res) {
                        console.log(res.data) // data
                    }
                })
            }
        })
    },
    chilkspec(e){
        var id = e.currentTarget.dataset.id;
        var index = e.currentTarget.dataset.index;
        var curProduct = this.data.curProduct;

        curProduct.specs.forEach(function(item,index,array){
            if(item.id == id){
                curProduct.specs[index].checked = true;
            }else{
                curProduct.specs[index].checked = false;
            }
        });

        if(curProduct.specs[index].num >= curProduct.specs[index].stock){
            curProduct.specs[index].num = curProduct.specs[index].stock;
            this.setData({
                plusSrc: "/images/cannot-plus.png"
            })
        }else{
            this.setData({
                plusSrc: "/images/can-plus.png"
            })
        }
        if(curProduct.specs[index].num <=1){
            curProduct.specs[index].num = 1;
            this.setData({
                minusSrc: "/images/cannot-minus.png"
            })
        }else{
            this.setData({
                minusSrc: "/images/can-minus.png"
            })
        }

        this.setData({
            curProduct:curProduct,
            curSpecIndex:index
        })
    }
})

